package com.yunzone.cloud.modules;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yunzone.cloud.common.entity.Result;
import com.yunzone.cloud.modules.payment.entity.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@RequestMapping("/order")
public class OrderController {
    private final String ADDR = "http://payment-provider";
    @Value("${server.port}")
    private String port;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private PaymentService paymentService;

    @RequestMapping("/query/{id}")
    //@SentinelResource(value = "fallback") //没有配置
    //@SentinelResource(value = "fallback", fallback = "fallbackHandler")//fallback只负责业务异常
    //@SentinelResource(value = "fallback", blockHandler = "blockHandler")//blockHandler只负责sentinel控制台配置违规
    @SentinelResource(value = "fallback",
            fallback = "fallbackHandler",
            blockHandler = "blockHandler",
            exceptionsToIgnore = IllegalArgumentException.class)//二者都配置
    public Result<Payment> fallback(@PathVariable Long id) {
        //Result<Payment> result =paymentService.query(id);
        Result<Payment> result = restTemplate.getForObject(ADDR + "/payment/query/" + id, Result.class, id);
        if (id == 4) {
            throw new IllegalArgumentException(" IllegalArgumentException,非法参数异常....");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }

    public Result blockHandler(@PathVariable("id") Long id, BlockException e) {
        Payment payment = new Payment(id, "nu11");
        return new Result<>(445, false, "sentinel限流，无此流水。exception内容" + e.getMessage(), payment);
    }

    public Result fallbackHandler(@PathVariable("id") Long id, Throwable e) {
        Payment payment = new Payment(id, "nu11");
        return new Result<>(444, false, "兜底异常fallbackHandler, exception内容" + e.getMessage(), payment);
    }
    @RequestMapping("/query/feign/{id}")
    public Result<Payment> feign(@PathVariable("id") Long id) {
        Result<Payment> result =paymentService.query(id);
        return result;
    }

}